<template>

  <div class=" player-container">
    <XyzTransitionGroup class="item-group" xyz="fade down-100% back-5">
      <!--    歌曲歌词播放页面-->
      <div class="Song-detail" :style="{ 'background': `url(${MusicStore.img})`}" v-if="Open">
        <div class="lyrics_div">
          <!--  关闭音乐播放页面的按钮-->
          <div class="down-close" @click="ToggleOpen">
            <el-icon>
              <ArrowDownBold/>
            </el-icon>
          </div>
          <!-- 留声机-->
          <div class="phonograph">
            <div class="box-1">
              <div :class="{'box-2':true, 'img-box-animation':true}"
                   :style="{ 'background': `url(${MusicStore.img})`,'animation-play-state':rotateState,'background-size': '240px 240px'}"></div>
            </div>
          </div>
          <!--  播放指针-->
          <div class="zhizhen-box" :style="{ 'transform': `rotate(${deg})`}">
            <img src="../assets/images/zhizhen.png" class="img-zhizhen">
          </div>
          <!-- 歌词-->
          <div class="geci" v-show="!changeLyricOrDanMu">
            <el-scrollbar ref="scrollbarRef" @scroll="scroll" :noresize="true">
              <p class="item-lyric"
                 :style="{'font-size': dialogue_index === indexHis ? '16px' : '14px','height': '30px','margin':0 ,'color':dialogue_index === indexHis ? 'red' : 'white'}"
                 v-for="(dialogue,dialogue_index) in MusicStore.Lyric"
                 :id="(dialogue_index)">
                {{ dialogue.text }}</p>
            </el-scrollbar>
          </div>
          <!--          歌词弹幕切换按钮-->
          <div class="current-button">
            <div :class="{'current-lyric':true,'current-change':!changeLyricOrDanMu}"
                 @click="ToggleText">歌词
            </div>
            <div :class="{'current-danmu': true,'current-change':changeLyricOrDanMu}" @click="ToggleText">弹幕</div>
          </div>
          <!--          发送弹幕的输入框-->
          <div class="danmu-iptbox" v-show="changeLyricOrDanMu">
            <span>点击我发送弹幕~</span>
            <span>|</span>
            <div class="submit-button">发送</div>
          </div>
          <!--          歌曲信息-->
          <div class="Player-title">
            <div style="color: white;font-size: 22px;padding-left: 150px">{{ MusicStore.song }}</div>
            <div class="current-song-info">
              <span class="current-singer">歌手：{{ MusicStore.singer }}</span>
              <span class="current-al">专辑：{{ MusicStore.al }}</span>
              <span class="current-source">歌曲来源：{{ MusicStore.songListName }}</span>
            </div>
          </div>

        </div>
      </div>
    </XyzTransitionGroup>


    <!--    歌曲信息-->
    <div class="song-info">
      <div class="img" @click="ToggleOpen">
        <img class="ava" :src="MusicStore.img" alt="" srcset="">
      </div>
      <div class="song-desc">
        <div class="desc">
          <span class="singer1"> {{ MusicStore.song }}</span>
        </div>
        <span class="singer2"> {{ MusicStore.singer }}</span>
        <div class="data-time">{{
            timeToMinute(TimeToSecond(MusicStore.dt) - (TimeToSecond(MusicStore.dt) - SongTimer))
          }}/{{ MusicStore.dt }}
        </div>
      </div>
    </div>
    <!--    播放控件-->
    <div class="controls">
      <audio :src="MusicStore.url" ref="audio"
             id="vue_player"
             class="bgMusic"
             @ended="overAudio"
             @play="onPlay"
             @pause="onPause"
             @timeupdate="updateTime"
      />
      <div class="button">
        <img style="width: 25px" src="../assets/icon/left.png" alt="" srcset="" @click="prevFun">
        <img v-if="State" @click="Toggle" style="width: 25px" src="../assets/icon/bofang.png" alt=""
             srcset="">
        <img v-else @click="Toggle" style="width: 25px" src="../assets/icon/zanting.png" alt=""
             srcset="">
        <img style="width: 25px" src="../assets/icon/right.png" alt="" srcset="" @click="nextFun">
      </div>
      <div class="time">
        <div :class="{'demo-progress':true,'progress-change':showPoint}" @mouseenter="showRedPoint">
          <div class="music-progress" @mousedown="grabFun('down')" @mouseup="grabFun('up')" @click="grabFun('click')"
               :style="{width:percentage +'px'}">
          </div>

        </div>
      </div>
      <div class="circle" v-show="showPoint"
           :style="{'left':(percentage-15)+'px'}">
      </div>
      <div :class="{'touch-box':showTouchBox}">

      </div>
    </div>
    <!--    展开按钮-->

    <div class="expandedList" v-if="MusicStore.MusicPlayList">
      <el-badge :value="MusicStore.MusicPlayList.length" :max="99" class="item">
        <el-icon :size="25" @click="OpenMusicList">
          <Expand/>
        </el-icon>
      </el-badge>
    </div>

  </div>
  <!--    弹出播放列表-->

  <div class="drawer" v-if="drawer">
    <el-scrollbar>
      <el-table :data="MusicStore.musicList" height="700" style="width: 100%" @cell-click="CellClick">
        <el-table-column prop="song" label="歌曲名"/>
        <el-table-column label="歌手">
          <template v-slot="{row}">
            {{ row.singer }}
          </template>
        </el-table-column>
        <el-table-column label="时长">
          <template v-slot="{row}">
            {{ row.dt }}
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, watch, nextTick} from "vue";
import {useMusicStore} from "../store/index.js"
import {TimeToSecond, timeToMinute, formatLyric} from "../utils/tools.js";
import {getLyric, getMusicUrl} from "../api/songlist.js";

const MusicStore = useMusicStore()

// 监听全局的点击事件
onMounted(() => {
  nextTick(() => {
    let node = document.querySelector('html')
    node.addEventListener('click', (e) => {
      if (drawer.value) {
        if (e.x < 1155) {
          drawer.value = false
        }
      }
    })
  })
})


// 进度条
let percentage = ref(0)
// 控制拖动进度条的触摸面积的显示隐藏
let showTouchBox = ref(false)
// 拖动进度条时的操作
const grabFun = (val) => {
  if (val === 'click') {
    let node = document.querySelector(".demo-progress")
    node.addEventListener("click", savePoint)
  }
  if (val === "down") {
    showTouchBox.value = true
    let node = document.querySelector("body")
    node.addEventListener("mousemove", savePoint)
    node.addEventListener("mouseup", RemoveSavePoint)
    node.addEventListener("mouseleave", RemoveSavePoint)
  }
}

let showPoint = ref(false)
// 鼠标放上去显示小红点
const showRedPoint = () => {
  showPoint.value = !showPoint.value
}

// 控制旋转的角度
let deg = ref('-30deg')
// 控制旋转的播放暂停
let rotateState = ref('')

let State = ref(false)
let audio = ref()
const overAudio = () => {
  State.value = false
}
const onPause = () => {
  audio.value.pause()
  State.value = false
  deg.value = '-30deg'
  rotateState.value = 'paused'
}
const onPlay = () => {
  audio.value.play()
  State.value = true
  deg.value = "0deg"
  rotateState.value = 'running'
}

// 上一曲
const prevFun = async () => {
  let index = MusicStore.musicList.findIndex(item => item.id === MusicStore.id)
  let MusicLyric = []
  const res = await getMusicUrl(MusicStore.musicList[index - 1].id)
  const res2 = await getLyric(MusicStore.musicList[index - 1].id)
  MusicLyric = res2.data.lrc.lyric
  //格式化歌词
  formatLyric(MusicLyric)
  MusicStore.musicList[index - 1].url = res.data.data[0].url
  MusicStore.changeCurrentPlayMusic(MusicStore.musicList[index - 1])
}
// 下一曲
const nextFun = async () => {
  let index = MusicStore.musicList.findIndex(item => item.id === MusicStore.id)
  let MusicLyric = []
  const res = await getMusicUrl(MusicStore.musicList[index + 1].id)
  const res2 = await getLyric(MusicStore.musicList[index + 1].id)
  MusicLyric = res2.data.lrc.lyric
  //格式化歌词
  formatLyric(MusicLyric)
  MusicStore.musicList[index + 1].url = res.data.data[0].url
  MusicStore.changeCurrentPlayMusic(MusicStore.musicList[index + 1])
}
// 歌曲计时器
let SongTimer = ref(0)

// 当前播放的事件回调
const updateTime = (e) => {
  let percent = audio.value.currentTime / audio.value.duration
  let sp = 1500 / 100
  percentage.value = (percent * 100 * sp)
  let num = parseInt(audio.value.currentTime)
  let obj = 0
  if (num !== obj) {
    obj = num
    SongTimer.value = obj
    LyricsGunDong()
  }

}

// 切换播放和暂停
const Toggle = () => {
  if (State.value) {
    onPause()
    State.value = false

  } else {
    onPlay()
    State.value = true
  }
}

// 拖动进度条的位置回调
let point = reactive({
  x: 0,
  y: 0
})

// 保存拖动位置的回调
function savePoint(event) {
  point.x = event.offsetX
  point.y = event.offsetY
  percentage.value = point.x
  audio.value.currentTime = percentage.value * (audio.value.duration / 1500)
}

// 移除监听
function RemoveSavePoint(event) {
  showTouchBox.value = false
  showPoint.value = false
  let node = document.querySelector("body")
  node.removeEventListener("mousemove", savePoint)
}

// 控制抽屉
const drawer = ref(false)
// 打开抽屉
const OpenMusicList = () => {
  drawer.value = !drawer.value
}
// 点击播放
const CellClick = async (row) => {
  let MusicLyric = []
  const res = await getMusicUrl(row.id)
  const res2 = await getLyric(row.id)
  MusicLyric = res2.data.lrc.lyric
  //格式化歌词
  formatLyric(MusicLyric)
  row.url = res.data.data[0].url
  MusicStore.changeCurrentPlayMusic(row)
}
//打开播放器
let Open = ref(false)
const ToggleOpen = () => {
  Open.value = !Open.value
  drawer.value = false
}

// 获取 滚动条的dom
const scrollbarRef = ref()
const scroll = (scroll) => {

}
let indexHis = ref(0)
// 歌词滚动
const LyricsGunDong = () => {
  if (Open.value) {
    for (let i = 0; i < MusicStore.Lyric.length; i++) { // 遍历歌词列表
      if (audio.value.currentTime <= MusicStore.Lyric[i].time) { // 判断当前是哪一句
        if (i >= 0) { // 确保不存在数组越界
          indexHis.value = i - 1
        }
        let current_height = (i - 1) * 30 // 计算当前文字绝对高度
        if (current_height > 30) {
          scrollbarRef.value.setScrollTop(current_height - 150)
        }
        break
      }
    }
  }
}

let changeLyricOrDanMu = ref(false)
// 播放器页页面 弹幕歌词切换
const ToggleText = () => {
  changeLyricOrDanMu.value = !changeLyricOrDanMu.value
}

</script>

<style lang="scss" scoped>

/*自定义动画类----顺时针旋转（使用这个动画的时候才设置动画执行时间）*/
@-webkit-keyframes changeright {

  0% {
    -webkit-transform: rotate(0deg);
  }

  50% {
    -webkit-transform: rotate(180deg);
  }

  100% {
    -webkit-transform: rotate(360deg);
  }
}


.drawer {
  position: absolute;
  top: -721px;
  height: 716px;
  width: 25%;
  right: 0;
  z-index: 99999;
  background-color: white;
  cursor: pointer;


}

.player-container {
  display: flex;
  width: 1500px;
  justify-content: space-between;
  position: relative;


  .Song-detail {
    position: absolute;
    top: -771px;
    height: 770px;
    width: 100%;
    overflow: hidden;
    transition: all 0.5s;


    .lyrics_div {
      height: 770px;
      width: 100%;
      text-align: center;
      padding-top: 100px;
      color: #fff;
      background-color: rgba(0, 0, 0, 0.5);
      backdrop-filter: blur(90px);
      background-position: center;
      position: relative;

      .geci {
        height: 420px;
        width: 600px;
        position: absolute;
        right: 0;
        top: 200px;
        text-align: left;
        padding-left: 150px;

        .item-lyric {
          transition: all 0.5s;
        }
      }

      .current-button {
        position: absolute;
        top: 150px;
        right: 330px;
        height: 30px;
        width: 120px;
        background-color: transparent;
        border: 1px solid white;
        border-radius: 15px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        cursor: pointer;


        .current-lyric {
          width: 55px;
          height: 26px;
          color: white;
          line-height: 26px;
          font-size: 14px;
        }

        .current-danmu {
          width: 55px;
          height: 26px;
          color: white;
          line-height: 26px;
          font-size: 14px;
        }

        .current-change {
          width: 55px;
          height: 26px;
          line-height: 26px;
          color: black;
          border-radius: 15px;
          font-size: 14px;
          background-color: white;
        }
      }

      .danmu-iptbox {
        position: absolute;
        top: 150px;
        right: 40px;
        height: 30px;
        width: 180px;
        background-color: transparent;
        border: 1px solid white;
        border-radius: 15px;
        text-align: left;
        display: flex;
        justify-content: space-around;

        span {
          font-size: 14px;
          line-height: 30px;
          color: white;
        }

        .submit-button {
          width: 30px;
          font-size: 14px;
          line-height: 30px;
          color: white;
          cursor: pointer;
        }
      }

      .Player-title {
        height: 100px;
        width: 600px;
        position: absolute;
        top: 60px;
        right: 0;
        text-align: left;


        .current-song-info {
          display: flex;
          justify-content: space-around;
          padding-left: 150px;
          margin-top: 20px;

          Span {
            font-size: 14px;
            color: white;
          }

          .current-singer {
            display: block;
            width: 100px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }

          .current-source {
            display: block;
            width: 180px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }

          .current-al {
            display: block;
            width: 120px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }

      //关闭按钮
      .down-close {
        position: absolute;
        top: 30px;
        left: 30px;
        line-height: 40px;
        height: 40px;
        width: 40px;
        font-size: 25px;
      }

      //  留声机
      .phonograph {
        position: absolute;
        top: 210px;
        left: 370px;
        height: 400px;
        width: 400px;
        background-color: #9e9898;
        border-radius: 50%;

        .box-1 {
          position: absolute;
          top: 20px;
          left: 20px;
          height: 360px;
          width: 360px;
          background-color: black;
          border-radius: 50%;
        }

        .box-2 {
          position: absolute;
          top: 60px;
          left: 60px;
          height: 240px;
          width: 240px;
          border-radius: 50%;
        }

      }

      // 顺时针动画
      .img-box-animation {
        -webkit-animation: changeright 20s linear infinite;
      }

      //  播放指针
      .zhizhen-box {
        position: absolute;
        top: 70px;
        left: 450px;
        height: 300px;
        width: 300px;
        border-radius: 50%;
        transform-origin: 10px 20px;
        transition: all 0.5s;


        .img-zhizhen {
          display: block;
          height: 100%;
        }
      }
    }


  }


  .song-info {
    display: flex;
    width: 450px;
  }


  .img {
    height: 80px;
    width: 80px;
    overflow: hidden;
    line-height: 80px;
    text-align: center;
    position: relative;


    .ava {
      width: 80%;
      height: 80%;
      vertical-align: middle;
      border-radius: 10px;
    }

  }

  .song-desc {
    display: flex;
    flex-direction: column;
    color: rgb(82 91 114);
    justify-items: center;
    justify-content: space-around;
    margin-left: 5px;

    .singer2 {
      font-size: 13px;
      color: gray;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .desc {
      display: flex;
      width: 200px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;

      .singer1 {
        font-size: 16px;
        color: black;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }

    }
  }

  .controls {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-right: 15%;
    width: 100%;

    .touch-box {
      position: absolute;
      top: -770px;
      left: 0;
      height: 850px;
      width: 100%;
      background-color: transparent;
      z-index: 999;
    }

    .circle {
      position: absolute;
      top: -8px;
      left: 200px;
      height: 15px;
      width: 15px;
      background-color: red;
      border-radius: 50%;

    }

    .button {
      display: flex;
      z-index: 2;

      img {
        display: block;
        margin: 15px;
      }
    }

    .time {
      display: flex;
      align-items: center;


      .demo-progress {
        position: absolute;
        top: -5px;
        left: 0;
        width: 1500px;
        height: 5px;
        border-radius: 5px;
        overflow: hidden;
        background-color: #dde2eb;
        transition: all 0.2s;
        z-index: 66;


        .music-progress {
          background-color: red;
          height: 100%;
          width: 250px;
          text-align: right;
          line-height: 5px;
          border-radius: 5px;
        }
      }

      .progress-change {
        height: 8px;
      }


      .data-time {
        margin-bottom: 3px;
      }
    }
  }

  .expandedList {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 30px;
  }
}


</style>

